<template>
  <div class="sales-orders-container">
    <h1 class="title">Sales Orders</h1>
    <el-button type="primary" @click="fetchOrders" class="refresh-button">Refresh</el-button>
    <el-table :data="orders" style="width: 100%" border>
      <el-table-column prop="order_id" label="Order ID" width="180" align="center" />
      <el-table-column prop="customerName" label="Customer Name" width="200" />
      <el-table-column prop="total_amount" label="Total Amount" sortable />
      <el-table-column prop="status" label="Status" sortable />
    </el-table>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const orders = ref([]);
    const customers = ref([]);

    const fetchOrders = async () => {
      const response = await axios.get('/api/sales/orders');
      orders.value = response.data;
      // 动态设置客户名称
      setCustomerNames();
    };

    const fetchCustomers = async () => {
      const response = await axios.get('/api/customers');
      customers.value = response.data;
    };

    // 动态设置客户名称
    const setCustomerNames = () => {
      orders.value.forEach((order) => {
        const customer = customers.value.find((c) => c.customer_id === order.customer_id);
        order.customerName = customer ? customer.customer_name : 'Unknown';
      });
    };

    onMounted(async () => {
      await fetchOrders();
      await fetchCustomers();
    });

    return {
      orders,
      fetchOrders,
    };
  },
};
</script>

<style scoped>
.sales-orders-container {
  padding: 20px;
  background-color: #f8f8f8;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.refresh-button {
  margin-bottom: 20px;
}

.el-table {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.el-table th.el-table__cell {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: bold;
  text-align: center !important;
}

.el-table td.el-table__cell {
  text-align: center;
}
</style>